<template>
  <view>
    <navbar :config="config"></navbar>
    <view class="pay-nums-box">
      <view class="pay-title">
        转入金额
      </view>
      <view class="pay-num">
        <text class="pay-tag">￥</text>
        <u-input class="pay-money" v-model="money" type="digit" />
      </view>
    </view>
    <view class="pay-way-box">
      <view class="pay-way">
        <text class="pay-title">转入方式</text>
        <view class="pay-item" @click.stop="pay_mode = 1">
          <view class="pay-item-left">
            <text class="iconfont3 pay-item-icon" style="color: #09BB07;">&#xe68a;</text>
            <text class="pay-item-name">微信支付</text>
          </view>
<!--      <view :class="['pay-item-right', pay_mode === 1 ? 'active-pay-item' : '']">	  </view> -->
		  <view class="top" v-if="pay_mode === 1">
		  	<icon type="success" color="#FF721B" size="17"></icon>
		  </view>
		  <view class="top" v-else style="width: 32rpx;height: 32rpx;border-radius: 50%;border: #FF721B solid 1rpx;"></view>
        </view>
        <view class="pay-item" @click.stop="pay_mode = 2">
          <view class="pay-item-left">
            <text class="iconfont3 pay-item-icon" style="color: #06B4FD;">&#xe60a;</text>
            <text class="pay-item-name">支付宝</text>
          </view>
		  <view class="top" v-if="pay_mode === 2">
		  	<icon type="success" color="#FF721B" size="17"></icon>
		  </view>
		  <view class="top" v-else style="width: 32rpx;height: 32rpx;border-radius: 50%;border: #FF721B solid 1rpx;"></view>
          <!-- <view :class="['pay-item-right', pay_mode === 2 ? 'active-pay-item' : '']"></view> -->
        </view>
        <!-- <view class="pay-item" @click.stop="pay_mode = 10">
          <view class="pay-item-left">
            <text class="iconfont3 pay-item-icon" style="color: #06B4FD;">&#xe60a;</text>
            <text class="pay-item-name">支付宝（Adapay）</text>
          </view>
          <view :class="['pay-item-right', pay_mode === 10 ? 'active-pay-item' : '']"></view>
        </view> -->
        <!-- <view class="pay-item" @click.stop="pay_mode = 12">
          <view class="pay-item-left">
            <text class="iconfont3 pay-item-icon" style="color: #06B4FD;">&#xe60a;</text>
            <text class="pay-item-name">支付宝（慧收钱）</text>
          </view>
          <view :class="['pay-item-right', pay_mode === 12 ? 'active-pay-item' : '']"></view>
        </view>
        <view class="pay-item" @click.stop="pay_mode = 14">
          <view class="pay-item-left">
            <text class="iconfont3 pay-item-icon" style="color: #06B4FD;">&#xe607;</text>
            <text class="pay-item-name">银行卡支付</text>
          </view>
          <view :class="['pay-item-right', pay_mode === 14 ? 'active-pay-item' : '']"></view>
        </view> -->
        <!-- <view class="pay-btn" @click.stop="showBanksModel = true" v-if="pay_mode == 14">
          选择快捷银行卡支付
        </view> -->
      </view>
	  <view class="pay-btn" @click.stop="goPayBtn">
	    转入
	  </view>
    </view>

    <!-- 银行卡弹窗 -->
    <u-popup v-model="showBanksModel" mode="bottom" height="65%" border-radius="20" closeable safe-area-inset-bottom
      :mask-close-able="false" z-index="500">
      <view class="banks-content">
        <view class="add" @click="banksHandler()">+ 管理银行卡</view>
        <view class="header">银行卡支付</view>
        <template>
          <view class="banks" v-if="banksList.length > 0">
            <scroll-view class="scroll-box" scroll-y="true">
              <radio-group>
                <label class="item" :class="{'gray': !item.valid}" v-for="(item, index) in banksList" :key="item.id"
                  @click="payBankWay(14, item.id)">
                  <view class="box">
                    <image :src="item.logo" mode="widthFix"></image>
                    <text class="bank_name">{{item.local_bank_name || item.bank_name}}</text>
                    <text>{{item.local_bank_card_type_name}}</text>
                  </view>
                  <view class="box">
                    <view class="name">（{{$mUtil.bankAccount(item.card_id)}}）</view>
                    <radio :value="String(item.id)" :checked="card_id == item.id" />
                  </view>
                </label>
              </radio-group>
            </scroll-view>
          </view>
          <noData v-if="banksList.length <= 0"></noData>
        </template>
        <view class="banks-pay" @click="$u.throttle(goPayBtn, 500)" v-if="banksList.length">
          <text class=" txt">确认支付</text>
        </view>
        <view class="banks-pay" @click="banksHandler()" v-else>
          <text class="txt">请先添加银行卡</text>
        </view>
      </view>
    </u-popup>

    <u-modal v-model="showPayModel" ref="payModel" title="确认支付" :show-cancel-button="true" @confirm="payConfirm"
      @cancel="payCancel" :async-close="true" z-index="900">
      <view class="slot-content">
        <view class="paybody">
          <view class="header-text">
            <text>请输入银行预留手机号发送的短信验证，切记他人索取拒绝提供。</text>
          </view>
          <view class="sms">
            <u-input v-model="sms_code" type="number" maxlength="6" :clearable="false" placeholder="请输入预留手机号验证码" />
            <view class="retry-gary" :class="{'retry': codeCount > 0}" @click="retrySms()"><text
                v-if="codeCount > 0">{{codeCount}}S后</text>重发</view>
          </view>
          <!-- <u-message-input mode="bottomLine" :maxlength="6"></u-message-input> -->
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script>
  let timer
  import {
    directBuy
  } from "@/api/personal-center.js"
  import noData from "@/components/noData/nodata.vue"
  export default {
    components: {
      noData
    },
    data() {
      return {
        config: {
          back: true, //false是tolbar页面 是则不写
          title: '转入',
          color: '#FFFFFF',
          // autoBack:true,
          //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
          backgroundColor: [1, "#FF721B"],
          statusBarFontColor: '#FFFFFF'
        },
        money: '',
        pay_mode: 1, // 支付方式
        showBanksModel: false,
        showPayModel: false,
        banksList: [], // 有效银行卡
        card_id: '', // 银行卡id
        sms_code: '', // 银行卡支付短信验证码
        codeCount: 10, // 银行卡支付短信验证码重发倒计时
        payment_id: '', // 预支付id,
      };
    },
    onShow() {
      this.getBanks()
    },
    methods: {
      getBanks() {
        this.$http.get('/usercard/list?valid=1').then(res => {
          if (res.code == 200) {
            this.banksList = res.list
            this.banksList.map(item => {
              item.logo = this.$mConfig.bankLink + item.local_bank_mark
            })
          }
        })
      },
      goPayBtn() {
        if (!this.money) {
          this.$mUtil.toast("请输入转入金额")
          return false
        } else if (!this.$mConfig.twoMinNum.test(this.money)) {
          this.$mUtil.toast("最多输入两位小数")
          return false
        };
        uni.showLoading({
          mask: true,
          title: '转入中...'
        })
        let data = {
          pay_mode: this.pay_mode, //1微信 2支付宝 0 余额
          money: this.money,
          client: "app",
        }
        // if (this.pay_mode == 12) {
        //   let locationObj = uni.getStorageSync('locationObj')
        //   data.longitude = locationObj.longitude.toFixed(4)
        //   data.latitude = locationObj.latitude.toFixed(4)
        // }
        // if (this.pay_mode == 14) {
        //   data.card_id = this.card_id
        //   if (!this.card_id) {
        //     if (this.banksList.length) {
        //       return this.$mUtil.toast('请先选择银行卡');
        //     }
        //     return this.$mUtil.toast('请先添加银行卡');
        //   }
        // }
        this.$http.post(directBuy, data).then(res => {
          if (res && res.code == 200) {
            let target = res.data.data
            console.log(target, 111111111)
            if (this.pay_mode == 1) {
              uni.requestPayment({
                provider: "wxpay",
                orderInfo: {
                  appid: target.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
                  noncestr: target.noncestr, // 随机字符串
                  package: target.package, // 固定值
                  partnerid: target.partnerid, // 微信支付商户号
                  prepayid: target.prepayid, // 统一下单订单号 
                  timestamp: target.timestamp, // 时间戳（单位：秒）
                  sign: target.sign // 签名，这里用的 MD5/RSA 签名
                },
                success: (res) => {
                  this.$mUtil.toast('支付成功');
                  setTimeout(() => {
                    uni.navigateBack({
                      delta: 1
                    })
                  }, 1000);
                },
                fail(e) {
                  uni.hideLoading()
                  console.log('fail:' + JSON.stringify(err));
                }
              })
            } else if (this.pay_mode == 2) {
              uni.requestPayment({
                provider: 'alipay',
                orderInfo: target.prePayOrderInfo,
                success: res => {
                  this.$mUtil.toast('支付成功');
                  setTimeout(() => {
                    uni.navigateBack({
                      delta: 1
                    })
                  }, 1000);
                },
                fail: function(err) {
                  uni.hideLoading()
                  console.log('fail:' + JSON.stringify(err));
                }
              });
            }
            // else if (this.pay_mode == 10) {
            //   // #ifdef APP-PLUS
            //   setTimeout(() => {
            //     this.showTip()
            //   }, 3000)
            //   if (target.expend) {
            //     this.jumpPay(target.expend.pay_info)
            //   } else if (target.status == 'failed') {
            //     this.$mUtil.toast(target.error_msg);
            //   }
            //   // #endif
            // } else if (this.pay_mode == 12) {
            //   // #ifdef APP-PLUS
            //   setTimeout(() => {
            //     this.showTip()
            //   }, 3000)
            //   if (target.qrCode) {
            //     this.jumpPay(target.qrCode)
            //   } else if (target.orderStatus == 'FAIL') {
            //     this.$mUtil.toast(target.respMsg);
            //   }
            //   // #endif
            // } else if (this.pay_mode == 14) {
            //   this.showPayModel = true
            //   this.payment_id = target.id
            //   this.codeCount = 10
            //   timer = setInterval(() => {
            //     this.codeCount--
            //     if (this.codeCount == 0) {
            //       clearInterval(timer)
            //     }
            //   }, 1000)
            // }
            // uni.hideLoading()
            // this.integral_able = res.data.integral_able;
            // uni.setStorageSync("personal", res.data)
          } else {
            // this.isLogin = false
            uni.hideLoading()
            this.$mUtil.toast('转入失败');
          }
        }).catch(err => {
          uni.hideLoading()
          this.$mUtil.toast('转入失败');
        })
      },
      jumpPay(qrCode) {
        if (qrCode) {
          let url = `alipays://platformapi/startapp?saId=10000007&qrcode=${qrCode}`
          if (plus.os.name == 'iOS') {
            plus.runtime.launchApplication({
              pname: 'com.eg.android.AlipayGphone',
              action: url,
            }, err => {
              console.log("err:" + JSON.stringify(err))
              this.$mUtil.toast('支付跳转失败，请选择其它支付方式');
            });
          } else if (plus.os.name == 'Android') {
            plus.runtime.openURL(url, err => {
              console.log("err:" + JSON.stringify(err))
              this.$mUtil.toast('支付跳转失败，请选择其它支付方式');
            }, 'com.eg.android.AlipayGphone');
          }
        }
      },
      showTip() {
        uni.showModal({
          title: '确认支付',
          content: '请确认当前转入订单是否支付',
          success: (success) => {
            if (success.confirm) {
              console.log('用户点击确定');
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1
                })
              }, 1000);
            } else if (success.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      },
      banksHandler() {
        uni.navigateTo({
          url: '/pages/order/banks/list'
        })
      },
      payBankWay(e, id) {
        this.pay_mode = e;
        this.card_id = id
      },
      retrySms() {
        if (this.codeCount > 0) return this.$mUtil.toast('请稍后重试');
        this.codeCount = 10
        uni.showLoading({
          title: '重发中...',
          mask: true
        })
        this.$http.post('/pay/order/kjRepeatSendSms', {
          payment_id: this.payment_id
        }).then(res => {
          uni.hideLoading()
          if (res.code == 200) {
            this.$mUtil.toast('短信验证码重发成功');
          } else {
            this.$mUtil.toast('服务异常! 请重试');
          }
        }).catch(err => {
          uni.hideLoading()
          // this.$mUtil.toast('服务异常！');
        })
      },
      payConfirm() {
        this.$refs.payModel.clearLoading()
        if (!this.sms_code) {
          return this.$mUtil.toast('短信验证码不能为空');
        }
        uni.showLoading({
          title: '转入中...',
          mask: true
        })
        this.$http.post('/pay/order/kjPayConfirm', {
          payment_id: this.payment_id,
          sms_code: this.sms_code
        }).then(res => {
          if (res.code == 200) {
            setTimeout(() => {
              uni.hideLoading()
              uni.navigateBack({
                delta: 1
              })
            }, 1000)
          }
        }).catch(err => {
          uni.hideLoading()
        })
      },
      payCancel() {
        this.$mUtil.toast('已取消转入');
      },
    }
  }
</script>

<style lang="scss" scoped>
  $padding: 65rpx;

  page{
  	background-color: #ffffff;
  }
  .pay-nums-box {
    width: 100%;
    height: 277rpx;
    // background-color: #f5f5f5;
    padding: 0 $padding;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .pay-title {
      font-size: 32rpx;
      font-family: PingFang SC, PingFang SC-Bold;
      font-weight: bold;
      color: #474747;
    }

    .pay-num {
      width: 100%;
      height: 120rpx;
      border-bottom: 1rpx solid #CCCCCC;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .pay-tag {
        font-size: 48rpx;
        font-family: PingFang SC, PingFang SC-Bold;
        font-weight: bold;
        color: #FF721B;
        flex-shrink: 0;
        padding-right: 5px;
      }

      .pay-money {

        // height: 100%;
        // .u-input__input{
        // 	height: 100%;
        // }
        .uni-input-placeholder {
          font-size: 28rpx;
          font-family: PingFang SC, PingFang SC-Regular;
          font-weight: 400;
          color: #AAAAAA;
        }

        .uni-input-input {
          color: #000000;
        }
      }
    }

  }

  .pay-way-box {
    width: 100%;
    // background-color: #f5f5f5;
	.pay-btn {
	  margin: 0 auto;
	  margin-top: 137rpx;
	  width: 90%;
	  // width: 630px;
	  height: 90rpx;
	  line-height: 90rpx;
	  background: #FF721B;
	  border-radius: 20rpx;
	  font-size: 32rpx;
	  font-family: PingFang SC, PingFang SC-Regular;
	  font-weight: 400;
	  color: #ffffff;
	  text-align: center;
	}
  }

  .pay-way {
    width: 100%;
    // min-height: calc(100vh - 277rpx );
    background-color: #fff;
    border-radius: 40rpx 40rpx 0 0;
    padding: 50rpx 65rpx 0;

    .pay-title {
      font-size: 32rpx;
      font-family: PingFang SC, PingFang SC-Bold;
      font-weight: 700;
      color: #333333;
    }

    .pay-item {
      margin-top: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .pay-item-left {
        display: flex;
        align-items: center;

        .pay-item-icon {
          font-size: 58rpx;
        }

        .pay-item-name {
          font-size: 28rpx;
          font-family: PingFang SC, PingFang SC-Regular;
          font-weight: 400;
          color: #666666;
          padding-left: 18rpx;
        }
      }
	  
	  .top {
	  	display: flex;
	  	align-items: center;
	  }

      .pay-item-right {
        flex-shrink: 0;
        width: 36rpx;
        height: 36rpx;
        background: #ffffff;
        border: 2rpx solid #FF721B;
        border-radius: 50%;
      }

      .active-pay-item {
        position: relative;

        &:before {
          content: '';
          position: absolute;
          left: 50%;
          top: 50%;
          width: 18rpx;
          height: 18rpx;
          background: #FF721B;
          border-radius: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }

  }

  .paybody {
    padding: 20rpx 30rpx;

    /deep/ .u-input {
      border-bottom: 2rpx solid #dcdfe6;
    }

    .header-text {
      margin-bottom: 20rpx;
    }

    .sms {
      display: flex;
      align-items: center;

      .retry-gary {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 180rpx;
        margin-left: 40rpx;
        padding: 20rpx 10rpx;
        background-color: #FF721B;
        border-radius: 10rpx;
        color: #fff;
      }

      .retry {
        background-color: gray;
      }
    }
  }

  .banks-content {
    height: 100%;
    padding: 80rpx 30rpx 0;

    .add {
      position: absolute;
      top: 30rpx;
      left: 30rpx;
      font-size: 30rpx;
      font-weight: bold;
      color: #FF721B;
    }

    .header {
      position: absolute;
      top: 30rpx;
      left: 50%;
      font-size: 30rpx;
      font-weight: bold;
      transform: translateX(-50%);
    }

    .no-data-view {
      margin-top: 10vh !important;
    }

    .banks-pay {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80%;
      position: fixed;
      bottom: 20rpx;
      left: 50%;
      color: #fff;
      border-radius: 10rpx;
      padding: 20rpx 0;
      text-align: center;
      font-size: 30rpx;
      transform: translateX(-50%);
      background-color: #FF721B;

      .txt {
        margin-right: 10rpx;
      }
    }

    .banks {
      width: 100%;
      height: 80%;
      overflow: hidden;

      .scroll-box {
        width: 100%;
        height: 100%;
      }
    }

    .item {
      // height: 100rpx;
      // display: flex;
      // align-items: center;
      display: block;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #E6E5E5;

      .box {
        display: flex;
        justify-content: space-between;
        align-items: center;

        &:first-child {
          margin-bottom: 10rpx;
        }

        .bank_name {
          font-size: 30rpx;
          font-weight: bold;
        }
      }

      image {
        width: 200rpx;
        height: auto;
      }

      .bank-icon {
        margin-right: 10rpx;
        color: #2f77f1;
        font-size: 50rpx;
        flex-shrink: 0;
      }

      .name {
        margin-right: 20rpx;
        font-size: 26rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .unbind {
        margin-left: auto;
        color: red;
        flex-shrink: 0;
      }
    }

    .gray {
      color: gray;

      .bank-icon {
        color: gray;
      }
    }
  }
</style>